package com.iraeta.service.sys.impl;

import com.iraeta.Config;
import com.iraeta.dao.main.DJFileDao;
import com.iraeta.entity.main.DJFile;
import com.iraeta.entity.main.DJFileProcessStatus;
import com.iraeta.uitl.ExcelUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;

@Service
public class FileProcessFrist {
    @Autowired
    Config config;
    @Autowired
    DJFileDao djFileDao;

    @Transactional
    public void processDjFile(DJFile djFile){
        try {
            String excelFilePath = config.OUTPUT_FILE_PATH + "/" + djFile.getDownloadPath();
            FileInputStream excelFile = new FileInputStream(excelFilePath);
            XSSFWorkbook workbook = new XSSFWorkbook(excelFile);
            XSSFSheet excelSheet = workbook.getSheetAt(0);
            int rows = excelSheet.getPhysicalNumberOfRows(); //行数
            int cols = excelSheet.getRow(0).getPhysicalNumberOfCells();//列数
            for(int row = 0;row< rows; ++row){
                Row rowObj = excelSheet.getRow(row);

                for (int col =0; col < cols; ++col){
                    Cell cell = rowObj.getCell(col);
                    System.out.print(ExcelUtil.getCellValue(cell).toString() + ' ');
                    if(col ==1)
                        System.out.println();
                }
            }
            workbook.close();
            djFile.setStatusId(DJFileProcessStatus.success);
            djFileDao.updateByPrimaryKey(djFile);
        }catch (Exception e){
            djFile.setMessage(e.getMessage());
            djFile.setStatusId(DJFileProcessStatus.error);
            djFileDao.updateByPrimaryKey(djFile);
        }
    }
}
